<template>
  <div class="map-container" ref="mapContainer"></div>
</template>

<script>
/* eslint-disable */
import { markRaw, watch } from 'vue'

export default {
  name: 'HairtailSchematicDiagram',
  props: {
    selectedSTCD: {
      type: String,
      default: ''
    },
    basinCode: {
      type: String,
      default: 'WDA'
    },
    // 选中改变前的方法，通过返回参数判断是否选中闪烁
    beforeChanged: {
      type: Function,
      default() {
        return true
      }
    },
    /**
     * 获取调度信息
     */
    dataGetter: {
      type: Function,
      default() {}
    },
    /**
     * 地图的定位和缩放信息
     */
    mapviewSetting: {
      type: Object,
      default() {
        return {
          WDA: {
            center: { lat: 35.960075850214805, lng: 117.095 },
            zoom: 9.6
          },
          WEB: {
            center: { lat: 35.35399848374364, lng: 118.26571726904453 },
            zoom: 8.9
          }
        }
      }
    },
    /**
     * 路径的配置
     */
    geojsonPath: {
      type: Object,
      default() {
        return {
          // 山东省全域
          // shandong: {}
          // 大汶河
          // WDA: {
          //   gaihuatuPath: 'data/generalizationData/DWH/gaihuatuDWHHairtail1.geojson',
          //   hedaoyujingPath: 'data/generalizationData/DWH/duanmian72.geojson',
          //   kuqunBoundary: 'data/generalizationData/DWH/ghtRegionBoundaryHairtail.geojson'
          // },
          // // 沂沭河流域
          // WEB: {
          //   gaihuatuPath: 'data/generalizationData/YSH/gaihuatuYSH.geojson'
          // }
          // YSH: { gaihuatuPath: 'data/generalizationData/YSH/gaihuatuYSH.geojson' },
        }
      }
    },
    onInit: {
      type: Function,
      default(manager, config, basinCode) {}
    },
    leafletConf: {
      type: Object,
      default() {
        return {
          zoom: 9,
          zoomSnap: 0.1,
          wheelPxPerZoomLevel: 180,
          doubleClickZoom: false,
          scrollWheelZoom: true,
          dragging: true
        }
      }
    }
  },
  data() {
    return {
      manager: null,
      shuikuDiaoduResult: [],
      hedaoyujingData: [],
      forewarnStationArray: [],
      forewarnRiverArray: [],
      gaihuatuData: null,
      needInitEvent: true, // 概化图事件只绑定一次
      pathObj: {}
    }
  },
  emits: ['update:selectedSTCD', 'clicked', 'layerOnload'],
  watch: {
    selectedSTCD: {
      handler() {
        this.startFlastBySTCD()
      }
    },
    geojsonPath: {
      handler() {
        this.pathObj = this.geojsonPath
        console.log('监听', this.pathObj)
      },

      immediate: true
    }
  },

  mounted() {
    // setTimeout(() => {
    // 初始化地图
    this.initManager()
    // }, 1000)
    setTimeout(() => {
      this.invalidateSize(true)
    }, 1000)
    this.$watch(
      () => {
        return this.basinCode
      },
      () => {
        this.init()
      },
      { immediate: true }
    )
  },
  beforeUnmount() {
    if (this.manager) {
      this.manager.destroy()
    }
  },
  methods: {
    // 初始化概化图
    init() {
      this.initGeneratilization().then((response) => {
        // 绑定事件，且只能绑定一次
        if (this.needInitEvent) {
          this.initGaihuatuEvent()
        }
        this.updateDepData()
        // 调用外部方法绘制额外的信息
        typeof this.onInit === 'function' && this.onInit(this.manager, this.pathObj, this.basinCode)
      })
    },
    // 初始化概化图管理
    initManager() {
      // 概化图的变量
      this.manager = markRaw(
        new Generalization.Manager({
          iconBasePath: 'generalization/icon/',
          page: 'page1',
          labelStyle: {
            // 字体大小
            fontSize: 8,
            // 字体颜色
            fontColor: '#00effe',
            // 是否显示边框
            border: true,
            // 边框颜色
            borderColor: '#00effe',
            // 内边距
            padding: 1,
            // 是否显示箭头
            borderArrow: true,
            // 是否背景
            fillBg: true,
            // 背景色颜色
            fillBgColor: '#00effe',
            // 有背景颜色时字体颜色
            fillBgFontColor: '#000000'
          },
          fillBgDataConfig: { class: 'ZQ', classField: 'STTYPE' }
        })
      )
    },
    // 以下为新概化图函数
    initGeneratilization() {
      const manager = this.manager
      const config = this.mapviewSetting[this.basinCode]

      if (!manager.map) {
        manager.initMap(this.$refs.mapContainer, {
          ...this.leafletConf
        })
        manager.map.on('click', function (e) {
          console.log(e)
        })
      }

      config && manager.map.flyTo(config.center, config.zoom, { animate: false })

      const requestArray = []
      // 添加概化图基础图层
      requestArray.push(this.initGaiHuaTuData())
      requestArray.push(this.initHedaoyujingData())
      return Promise.all(requestArray)
    },

    // 基础图层初始化
    initGaiHuaTuData() {
      return new Promise((resolve, reject) => {
        let path
        try {
          path = this.pathObj[this.basinCode].gaihuatuPath
        } catch (e) {
          return reject()
        }
        if (!path) {
          return resolve()
        }
        fetch(path)
          .then((response) => {
            return response.json()
          })
          .then((data) => {
            this.gaihuatuData = markRaw(data)
            this.startFlastBySTCD()
            this.manager.initGaiHuaTuData(data)
            resolve()
          })
      })
    },

    // 预警河道拓扑数据加载
    initHedaoyujingData() {
      return new Promise((resolve, reject) => {
        let path
        try {
          path = this.pathObj[this.basinCode].hedaoyujingPath
        } catch (e) {
          return reject()
        }
        if (!path) {
          return resolve()
        }
        fetch(path)
          .then((response) => {
            return response.json()
          })
          .then((data) => {
            this.hedaoyujingData = markRaw(data)
            resolve()
          })
      })
    },

    // 根据预报结果设置概化图上的预警状态
    changeForewarningStatus() {
      const manager = this.manager
      if (this.forewarnStationArray.length > 0) {
        this.clearForewarningStatus()
      }
      this.shuikuDiaoduResult.forEach((element) => {
        if (element.wnstatus > 0) {
          this.forewarnStationArray.push(element)
          manager.updateMarkerWnStatus(element.stcd, element.wnstatus)
          if (element.pmt === 2) {
            // 水位站、水文站
            let riverStation = this.hedaoyujingData.features.find((ele) => {
              return element.stcd == ele.properties.stcd
            })
            this.forewarnRiverArray.push({
              OCD: riverStation.properties.OCD1,
              FCD: riverStation.properties.FCD1,
              wnstatus: element.wnstatus
            })
            manager.updatePathWnStatus(
              riverStation.properties.FCD1,
              riverStation.properties.OCD1,
              element.wnstatus + 1
            )
          }
        }
      })
      this.$emit('layerOnload')
    },

    // 将预警结果从概化图中清除
    clearForewarningStatus() {
      const manager = this.manager

      // 清除站点预警
      this.forewarnStationArray.forEach((element) => {
        manager.updateMarkerWnStatus(element.stcd, 0)
      })
      this.forewarnStationArray = markRaw([])
      // 清除河道预警
      this.forewarnRiverArray.forEach((element) => {
        manager.updatePathWnStatus(element.FCD, element.OCD, 0)
      })
      this.forewarnRiverArray = markRaw([])
    },

    // 初始化事件
    initGaihuatuEvent() {
      const manager = this.manager
      const self = this

      manager.on('marker-click', (e) => {
        console.log(e, 7766)
        const target = e.data.feature
        const res = this.beforeChanged(target)
        if (target && res) {
          // console.log(manager.map.getZoom(),manager.map.getCenter())
          this.$emit('update:selectedSTCD', e.data.feature?.properties?.STCD)
          self.$emit('clicked', e.data.feature, manager)
          self.$emit('clickedData', e.data.feature?.properties?.STCD)

          this.startFlastBySTCD()
        }
      })

      manager.on('region-click', (e) => {
        const target = e.data.feature

        const res = this.beforeChanged(target)
        if (target && res) {
          self.$emit('clicked', e.data.feature, manager)

          this.startFlastBySTCD()
        }
      })

      this.needInitEvent = false
    },

    // 开始闪烁
    startFlash(latLng) {
      this.manager.updateHighlightMarker(latLng)
    },

    // 清空闪烁
    clearFlash() {
      this.manager.removeHighlightMarker()
    },

    // 根据STCD 进行闪烁
    startFlastBySTCD() {
      console.log(88888)

      this.clearFlash()

      if (this.gaihuatuData) {
        const target = this.gaihuatuData.features.find(
          (item) => item.properties.STCD === this.selectedSTCD && this.selectedSTCD
        )

        const res = this.beforeChanged(target)
        if (target && res) {
          const [lng, lat] = target.geometry.coordinates
          this.startFlash({ lat, lng })
        }
      }
    },

    // 设置初始化尺寸
    invalidateSize(fit = true) {
      this.manager.map.invalidateSize(fit)
    },

    // 拉取新的数据
    updateDepData() {
      // 获取调度数据: 通过外部的方法去获取数据
      if (this.dataGetter) {
        const resp = this.dataGetter()
        if (resp instanceof Promise) {
          resp
            .then((data) => {
              this.shuikuDiaoduResult = markRaw(data || [])
              this.changeForewarningStatus()
            })
            .catch(() => {
              this.shuikuDiaoduResult = markRaw([])
            })
        } else if (resp) {
          this.shuikuDiaoduResult = markRaw(resp)
          this.changeForewarningStatus()
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
// 设置leaflet地图的背景颜色
.map-container {
  background-color: #122746;
  width: 100%;
  &:focus-visible {
    outline: none;
  }
}
</style>
